import axios from "axios";
import { useUserStore } from "@/stores/user.store";
import { showToast } from "vant";
import "vant/lib/toast/style";

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  withCredentials: false,
  timeout: 30000,
});

service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers["Authorization"] = userStore.token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code != 200) {
      showToast({
        message: res.msg || "接口调用错误",
      });
      return Promise.reject(res);
    } else {
      return res.result;
    }
  },
  (error) => {}
);

export function get(url, params) {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params: params,
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        console.log(" get err:", err);
        reject(err);
      });
  });
}

export function post(url, data) {
  // console.log(contentType ? contentType : 'application/json')
  return new Promise((resolve, reject) => {
    service
      .post(url, data)
      // .then((res) => checkLogin(res))
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        // console.log(' post err res:', err)
        reject(err);
      });
  });
}

export default service;
